package com.algorithm;

/**
 * @author: sun.hongliang
 * @create: 2019/07/02 11:48
 */
public class AddTwoSumTest {
    public static void main(String[] args) {
        final ListNode listNode1 = initListNode1();
        LinkListPrint.printListNode(listNode1);
        final ListNode listNode2 = initListNode2();
        LinkListPrint.printListNode(listNode2);
        final ListNode listNode = addTwoNumbers(listNode1, listNode2);
        LinkListPrint.printListNode(listNode);
    }


    public static ListNode initListNode1() {
        ListNode head = new ListNode(2);
        ListNode one = new ListNode(4);
        ListNode two = new ListNode(3);
        head.next = one;
        one.next = two;
        return head;
    }

    public static ListNode initListNode2() {
        ListNode head = new ListNode(5);
        ListNode one = new ListNode(6);
        ListNode two = new ListNode(4);
        head.next = one;
        one.next = two;
        return head;
    }


    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode p = head;
        int mod = 0;
        while (l1 != null || l2 != null) {
            int l1v = l1 != null ? l1.val : 0;
            int l2v = l2 != null ? l2.val : 0;
            int result = l1v + l2v + mod;
            mod = result >= 10 ? 1 : 0;
            result = result >= 10 ? result - 10 : result;
            p.next = new ListNode(result);
            p = p.next;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (mod == 1)
            p.next = new ListNode(1);
        return head.next;
    }
}
